// pages/index/index.js
Page({
  data: {
    mode: 'focus',
    time: 1500, // 25分钟，单位：秒
    displayTime: '25:00',
    isRunning: false,
    timer: null
  },

  onLoad(options) {
    this.initTimer();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (this.data.isRunning && this.data.lastPauseTime) {
      const now = Date.now();
      const diff = Math.floor((now - this.data.lastPauseTime) / 1000);
      const newTime = Math.max(0, this.data.time - diff);
      this.setData({
        time: newTime,
        displayTime: this.formatTime(newTime),
        lastPauseTime: null
      });
      if (newTime > 0) {
        this.startTimer();
      } else {
        this.handleTimerComplete();
      }
    }
  },

  onHide() {
    if (this.data.isRunning) {
      this.setData({ lastPauseTime: Date.now() });
      if (this.data.timer) {
        clearInterval(this.data.timer);
        this.setData({ timer: null });
      }
    }
  },

  onUnload() {
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  },

  // 初始化计时器
  initTimer() {
    const time = this.data.mode === 'focus' ? 1500 : 300;
    this.setData({
      time,
      displayTime: this.formatTime(time),
      isRunning: false
    });
    if (this.data.timer) {
      clearInterval(this.data.timer);
      this.setData({ timer: null });
    }
  },

  // 切换模式
  switchMode(e) {
    const mode = e.currentTarget.dataset.mode;
    this.setData({ mode });
    this.initTimer();
  },

  // 切换计时器状态
  toggleTimer() {
    if (!this.data.isRunning) {
      this.startTimer();
    } else {
      this.pauseTimer();
    }
  },

  // 开始计时
  startTimer() {
    if (this.data.time <= 0) return;
    
    this.setData({ isRunning: true });
    const timer = setInterval(() => {
      if (this.data.time <= 0) {
        this.handleTimerComplete();
        return;
      }
      
      const time = this.data.time - 1;
      this.setData({
        time,
        displayTime: this.formatTime(time)
      });
    }, 1000);
    
    this.setData({ timer });
  },

  // 暂停计时
  pauseTimer() {
    if (this.data.timer) {
      clearInterval(this.data.timer);
      this.setData({
        timer: null,
        isRunning: false
      });
    }
  },

  // 处理计时完成
  handleTimerComplete() {
    this.pauseTimer();
    wx.vibrateLong();
    
    // 创建音频实例
    const audio = wx.createInnerAudioContext();
    audio.src = './audio/silent.mp3';
    audio.play();

    // 显示提示
    wx.showToast({
      title: this.data.mode === 'focus' ? '专注完成！' : '休息结束！',
      icon: 'success',
      duration: 2000
    });

    // 切换模式并重新初始化计时器
    setTimeout(() => {
      const newMode = this.data.mode === 'focus' ? 'rest' : 'focus';
      this.setData({ mode: newMode });
      this.initTimer();
    }, 2000);
  },

  // 格式化时间
  formatTime(seconds) {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
  },

  // 测试音频播放
  testAudio: function() {
    const innerAudioContext = wx.createInnerAudioContext()
    innerAudioContext.src = './audio/silent.mp3'
    innerAudioContext.onError((res) => {
      console.error('音频播放失败：', res.errMsg)
      wx.showToast({
        title: '音频播放失败',
        icon: 'none'
      })
    })
    innerAudioContext.play()
  },
})